<template>
    <el-container>
      <el-header>新建作品</el-header>
      <el-main>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="书名" v-if="isCreatingBook">
            <el-input v-model="form.bookName"></el-input>
          </el-form-item>
          <el-form-item label="分类" v-if="isCreatingBook">
            <el-select v-model="form.kindId" placeholder="请选择分类">
              <el-option
                v-for="kind in kinds"
                :key="kind.idkind"
                :label="kind.kindName"
                :value="kind.idkind">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="章节标题" v-if="!isCreatingBook">
            <el-input v-model="form.chapName"></el-input>
          </el-form-item>
          <el-form-item label="章节内容" v-if="!isCreatingBook">
            <el-input type="textarea" v-model="form.content"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveDraft">保存草稿</el-button>
            <el-button type="primary" @click="publishWork">发布</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        isCreatingBook: true, // Flag to determine if we are creating a new book or a chapter
        form: {
          bookName: '',
          kindId: '',
          chapName: '',
          content: ''
        },
        kinds: []
      };
    },
    created() {
      this.fetchKinds();
    },
    methods: {
      fetchKinds() {
        axios.get('/api/kinds')
          .then(response => {
            this.kinds = response.data;
          })
          .catch(error => {
            console.error('获取分类失败:', error);
          });
      },
      saveDraft() {
        // Save draft logic (e.g., save to localStorage or backend)
      },
      publishWork() {
        if (this.isCreatingBook) {
          // Publish new book
          axios.post('/api/books', this.form)
            .then(response => {
              console.log('书籍发布成功');
            })
            .catch(error => {
              console.error('发布书籍失败:', error);
            });
        } else {
          // Publish new chapter
          axios.post('/api/chapters', this.form)
            .then(response => {
              console.log('章节发布成功');
            })
            .catch(error => {
              console.error('发布章节失败:', error);
            });
        }
      }
    }
  }
  </script>
  